﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Clmp.Data.DBEntity
{
    /// <summary>
    /// 事务上下文
    /// </summary>
    internal static class TransactionContext
    {
        [ThreadStaticAttribute]
        private static SqlConnection _connection;
        /// <summary>
        /// 获取当前事务的连接
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <returns>Connection对象</returns>
        public static SqlConnection GetConnection(string connectionString)
        {
            if (InTransaction)
            {
                if (_connection == null)
                {
                    _connection = new SqlConnection(connectionString);
                    _connection.Open();
                    _dbTransaction = _connection.BeginTransaction();

                    //TODO:DEBUG
                    Debug("\t create transaction conn.");

                }
                else
                {
                    if (connectionString != _connection.ConnectionString)
                        throw new System.Data.DataException("事物中的数据连接必须使用相同的连接字符串。");
                }
                //TODO:DEBUG
                Debug("\t get transaction conn.");
                return _connection;
            }
            return null;
        }

        [ThreadStaticAttribute]
        private static SqlTransaction _dbTransaction;
        /// <summary>
        /// 当前Sql数据库事务
        /// </summary>
        public static SqlTransaction DbTransaction
        {
            get { return _dbTransaction; }
            set { _dbTransaction = value; }
        }
        /// <summary>
        /// 是否在事务中
        /// </summary>
        public static bool InTransaction 
        {
            get { return Transaction.IsInit; }
        }
        /// <summary>
        /// 事务清空
        /// </summary>
        public static void Clear()
        {
            if (_dbTransaction != null)
            {
                _dbTransaction.Dispose();
                _dbTransaction = null;
            }
            if (_connection != null)
            {
                _connection.Dispose();
                _connection = null;
            }
        }

        [System.Diagnostics.Conditional("DEBUG")]
        internal static void Debug(string msg)
        {
            Console.WriteLine(msg);
        }
    }
}
